package java基础知识;

/**
 * @author coderFu
 * @create 2022/3/12
 * 线程独享变量，做个每个线程之间的数据隔离
 *
 */
public class CoderThreadLocal {

    private static ThreadLocal<Integer> var = new ThreadLocal<>();

    public static void main(String[] args) {


        // 使用lambda表达式简单模拟

        Thread t1 = new Thread(()->{
            var.set(10);
            var.set(100);
            System.out.println("当前的线程为"+Thread.currentThread().getName());
            for (int i = 0; i<5; i++){
                System.out.println("当前线程中ThreadLocal中的值为："+var.get());
            }
        },"coderDemo1");


        Thread t2 = new Thread(()->{
            var.set(15);
            System.out.println("当前的线程为"+Thread.currentThread().getName());
            for (int i = 0; i<5; i++){
                System.out.println("当前："+Thread.currentThread().getName()+var.get());
            }
        },"coderDemo2");

        t1.start();
        t2.start();



    }
}
